﻿using HslCommunication.Secs.Types;
using System.Collections.ObjectModel;
using System.Windows;
using WpfApp.Exceptions;
using WpfApp.Uers;
using MessageBox = HandyControl.Controls.MessageBox;

namespace WpfApp.Views
{
    public class UserItem
    {
        public string Name { get; set; } = string.Empty;
    }

    /// <summary>
    /// UserManagerWindow.xaml 的交互逻辑
    /// </summary>
    public partial class UserManagerWindow : Window
    {
        public ObservableCollection<UserItem> Users { get; set; }

        private readonly UserManager _userManager;
        public UserManagerWindow(UserManager userManager)
        {
            this.DataContext = this;
            _userManager = userManager;
            Users = new ObservableCollection<UserItem>();
            Loaded += UserManagerWindow_Loaded;
            InitializeComponent();
        }

        private void UserManagerWindow_Loaded(object sender, RoutedEventArgs e)
        {
            _userManager.Users.ForEach((item) =>
            {
                Users.Add(new UserItem() { Name = item.Name });
            });
        }

        private void RegisterButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.UserNameTextBox.Text) || string.IsNullOrWhiteSpace(this.RegisterPasswordBox.Password))
            {
                MessageBox.Show("用户名或卡号为空！", "用户提示");
                return;
            }

            try
            {
                _userManager.AddUser(new User() { Name = this.UserNameTextBox.Text, UserId = this.RegisterPasswordBox.Password });
                MessageBox.Show("注册成功！", "用户提示");
                this.UserNameTextBox.Text = string.Empty;
                this.RegisterPasswordBox.Password = string.Empty;
            }
            catch (UserFriendlyException ex)
            {
                MessageBox.Show(ex.Message, "用户提示");
            }
        }

        private void UnregisterButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.UnregisterPasswordBox.Password))
            {
                MessageBox.Show("卡号为空！", "用户提示");
                return;
            }

            _userManager.RemoveUser(this.UnregisterPasswordBox.Password);
            this.UnregisterPasswordBox.Password = string.Empty;
            MessageBox.Show("注销成功！", "用户提示");
        }

        private void UpdateButton_Click(object sender, RoutedEventArgs e)
        {
            Users.Clear();
            _userManager.Users.ForEach((item) =>
            {
                Users.Add(new UserItem() { Name = item.Name });
            });
        }
    }
}
